package com.meituan.catering.management.product.biz.service.impl;

import com.meituan.catering.management.common.model.biz.PageBO;
import com.meituan.catering.management.common.model.biz.UserContextBO;
import com.meituan.catering.management.common.model.enumeration.BusinessTypeEnum;
import com.meituan.catering.management.product.api.http.model.request.SearchProductHttpRequest;
import com.meituan.catering.management.product.biz.model.ProductBO;
import com.meituan.catering.management.product.biz.model.converter.ProductBOConverter;
import com.meituan.catering.management.product.biz.service.ProductAccessoryBizService;
import com.meituan.catering.management.product.biz.service.ProductBizService;
import com.meituan.catering.management.product.biz.service.ProductMethodBizService;
import com.meituan.catering.management.product.dao.mapper.ProductAccessoryMapper;
import com.meituan.catering.management.product.dao.mapper.ProductMapper;
import com.meituan.catering.management.product.dao.model.ProductAccessoryDO;
import com.meituan.catering.management.product.dao.model.ProductDO;
import com.meituan.catering.management.product.dao.model.ProductMethodDO;
import com.meituan.catering.management.product.dao.model.request.SearchProductDataRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * {@link ProductBizService}的核心实现
 */
@Service
public class ProductBizServiceImpl implements ProductBizService {

    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductAccessoryBizService productAccessoryBizService;
    @Resource
    private ProductMethodBizService productMethodBizService;
    /**
     * 混合查询
     * @param userContextBO
     * @param request
     * @return PageBO
     */
    @Override
    public PageBO<ProductBO>  searchForPage(UserContextBO userContextBO, SearchProductHttpRequest request) {
       SearchProductDataRequest searchProductDataRequest=this.buildDataRequest(userContextBO,request);
        /*1.查询检索到的总记录*/
        int count = productMapper.countForPage(searchProductDataRequest);
        PageBO<ProductBO> shopPageBO = this.buildPageBO(request, count);
        if (count > 0) {
            List<ProductDO> ProductDOs = this.productMapper.searchForPage(searchProductDataRequest);
            /**
             * 根据ids 批量查询商品子项
             */
            List<ProductBO> collect = ProductDOs.stream().map((item) -> {
                List<ProductBO.AccessoryGroup> accessoryGroups = this.productAccessoryBizService.findAllByProductId(userContextBO.getTenantId(), item.getId());
                List<ProductBO.MethodGroup> methodGroups = this.productMethodBizService.findAllByProductId(userContextBO.getTenantId(), item.getId());
                ProductBO productBO = ProductBOConverter.fromDO(item);
                productBO.getAccessoryGroups().addAll(accessoryGroups);
                productBO.getMethodGroups().addAll(methodGroups);
                return productBO;
            }).collect(Collectors.toList());

            shopPageBO.getRecords().addAll(collect);
          //  shopPageBO.getRecords().addAll(ProductDOs.stream().map(ProductBOConverter::fromDO).collect(Collectors.toList()));
            return shopPageBO;
        }
           return  shopPageBO;

    }

    /**
     * 根据id查询详情页
     * @param userContextBO
     * @param id
     * @return ProductBO
     */
    @Override
    public ProductBO findById(UserContextBO userContextBO, Long id) {
        ProductDO productDO = productMapper.findById(userContextBO.getTenantId(), id);
        if (productDO == null) {
            throw new IllegalArgumentException("无法找到id：" + id + " 的菜品");
        } else {
            /**
             * 找到该商品  在根据商品id 查询加料组集合
             */
            List<ProductBO.AccessoryGroup> accessoryGroups = this.productAccessoryBizService.findAllByProductId(userContextBO.getTenantId(), id);
            /**
             * 找到该商品  在根据商品id 查询做法组集合
             */
            List<ProductBO.MethodGroup> methodGroups = this.productMethodBizService.findAllByProductId(userContextBO.getTenantId(), id);

            ProductBO productBO = ProductBOConverter.fromDO(productDO);
            productBO.getAccessoryGroups().addAll(accessoryGroups);
            productBO.getMethodGroups().addAll(methodGroups);
            return productBO;
        }

    }


    /**
     *  查询请求 构建 DO 请求体
     * @param userContext
     * @param request
     * @return
     */
    private SearchProductDataRequest buildDataRequest(UserContextBO userContext, SearchProductHttpRequest request) {
        SearchProductDataRequest searchShopDataRequest=new SearchProductDataRequest();
        searchShopDataRequest.setTenantId(userContext.getTenantId());
        searchShopDataRequest.setSkip((request.getPageIndex()-1)*request.getPageSize());
        searchShopDataRequest.setSize(request.getPageSize());
        if (request.getCondition().getEnabled()!=null){
            searchShopDataRequest.setEnabled(request.getCondition().getEnabled()? 1:0);
        }
        /**
         * 模糊匹配 菜品名
         */
        if (request.getCondition().getName()!=null && request.getCondition().getName()!=""){
            searchShopDataRequest.setName("%"+request.getCondition().getName()+"%");
        }
        /**
         * 精确匹配
         */
        searchShopDataRequest.setUnitOfMeasure(request.getCondition().getUnitOfMeasure());
        /**
         * 转换价格区间
         */
        searchShopDataRequest.setMinPrice(request.getCondition().getUnitPrice().getFrom());
        searchShopDataRequest.setMaxPrice(request.getCondition().getUnitPrice().getTo());
        List<String> sortStr= new LinkedList<String>();
        /**
         * 处理排序逻辑
         */
        for (SearchProductHttpRequest.SortField data:request.getSortFields()) {
            String sortRule=data.getAsc() ? "ASC":"DESC";
            String field=data.getField();
            /**
             * 拼接排序字符串
             */
            sortStr.add(field+" "+sortRule);
        }
        searchShopDataRequest.setSortByClause(sortStr);
        return searchShopDataRequest;
    }


    private PageBO<ProductBO> buildPageBO(SearchProductHttpRequest request, int totalCount) {
        PageBO<ProductBO> shopPageBO = new PageBO();
        shopPageBO.setTotalCount(totalCount); //总记录
        shopPageBO.setPageSize(request.getPageSize());
        shopPageBO.setTotalPageCount(totalCount / request.getPageSize() + (totalCount % request.getPageSize() == 0 ? 0 : 1));
        if (request.getPageIndex() > shopPageBO.getTotalPageCount()) {
            shopPageBO.setPageIndex(shopPageBO.getTotalPageCount());
        } else {
            shopPageBO.setPageIndex(request.getPageIndex());
        }

        return shopPageBO;
    }






}
